package com.hualian.distribution.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hualian.system.common.Constants;
import com.hualian.user.service.UserService;
@Service
public class DistributionService {

	@Autowired
	private UserService userService;
	
	/**
	 * 注册成功奖励邀请人
	 * @param userId
	 */
	public int prize(int userId) {
		Map<String, Object> userInfo = userService.getById(userId).get(0);
		// 判断是否存在上级id
		if (userInfo.get("parentId") != null && userInfo.get("parentId") != "") {
			int parentId = (int) userInfo.get("parentId");
			if (userService.getById(parentId) != null) {
				// 每注册成功奖励邀请人
				Map<String, Object> parentInfo = userService.getById(parentId).get(0);
				float prize = Constants.PRIZE;
				float amountLeft = (float) parentInfo.get("amount_left") + prize;
				parentInfo.put("amount_left", amountLeft);
				int res = userService.updateUser(parentInfo);
				if (res == 0) {
					System.out.println("奖励邀请人数据库操作异常！");
				}
				return res;
			}
		}
		return 0;
	}

	/**
	 * 计算分销收益
	 * @param userId
	 * @param income
	 */
	public void calculator(int userId,float income) {
		Map<String, Object> userInfo = userService.getById(userId).get(0);
		// 判断是否存在上级id
		if (userInfo.get("parentId") != null && userInfo.get("parentId") != "") {
			int parentId = (int) userInfo.get("parentId");
			// 第一级分销计算收益
			Map<String, Object> parentInfo = userService.getById(parentId).get(0);
			float amountLeft = (float) ((float) parentInfo.get("amount_left") + income*0.5);
			parentInfo.put("amount_left", amountLeft);
			int res = userService.updateUser(parentInfo);
			if (res == 0) {
				System.out.println("分销数据库操作异常！");
			}
			//判断是否存在第二级父id
			if (parentInfo.get("parentId") != null && parentInfo.get("parentId") != "") {
				int grandId = (int) parentInfo.get("parentId");
				// 第二级分销计算收益
				Map<String, Object> grandInfo = userService.getById(grandId).get(0);
				amountLeft = (float) parentInfo.get("amount_left") + income;
				grandInfo.put("amount_left", amountLeft);
				int result = userService.updateUser(grandInfo);
				if (result == 0) {
					System.out.println("分销数据库操作异常！");
				}
			}
		}

	}
	
	
}
